package com.wzh.borrow.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import com.wzh.borrow.entity.UserEntity;
import com.wzh.borrow.service.UserService;
import com.wzh.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wzh.borrow.entity.BorrowEntity;
import com.wzh.borrow.service.BorrowService;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author wzh
 * @email 1281204121@qq.com
 * @date 2022-01-27 21:23:52
 */
@RestController
@RequestMapping("borrow/borrow")
public class BorrowController {
    @Autowired
    private BorrowService borrowService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(token);
        params.put("tel",claims.getId());
        PageUtils page = borrowService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{bid}")
    public R info(@PathVariable("bid") Integer bid){
		BorrowEntity borrow = borrowService.getById(bid);

        return R.ok().put("borrow", borrow);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody BorrowEntity borrow,HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(token);
        borrow.setUid(Integer.parseInt(claims.getId()));
        borrow.setCreateDate(new Date());
        borrow.setState("还款中");
		borrowService.save(borrow);
        UserEntity byId = userService.getById(borrow.getBuid());
        byId.setMoney(byId.getMoney()-borrow.getMoney());
        userService.updateById(byId);
        rabbitTemplate.convertAndSend("msg",borrow);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody BorrowEntity borrow){
		borrowService.updateById(borrow);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] bids){
		borrowService.removeByIds(Arrays.asList(bids));

        return R.ok();
    }

}
